package com.lcx.plugin.tool;

import cn.hutool.core.collection.CollUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author daxiong
 * @date 2023/6/16 下午5:08
 */
public class ListSplitUtil {
    public static final int LIST_IN_SIZE = 50;
    public static final int MAX_LIST_IN_SIZE = 500;

    /**
     * List分割
     *
     * @param list
     * @return java.util.List<java.util.List < T>>
     * @author daxiong
     * @date 2021/8/4 下午4:23
     */
    public static <T> List<List<T>> groupList(List<T> list) {
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<List<T>> listGroup = new ArrayList<>();
        int listSize = list.size();
        // 子集合的长度
        int toIndex = LIST_IN_SIZE;
        for (int i = 0; i < list.size(); i += LIST_IN_SIZE) {
            if (i + LIST_IN_SIZE > listSize) {
                toIndex = listSize - i;

            }
            List<T> newList = list.subList(i, i + toIndex);
            listGroup.add(newList);
        }
        return listGroup;
    }

    /**
     * sql语句 in超出最大值后，拆分list，查询
     *
     * @param consumer
     * @param originList
     * @return void
     * @author daxiong
     * @date 2021/8/4 下午4:31
     */
    public static <T> void iterationExecuteConsumer(Consumer<List<T>> consumer, List<T> originList) {
        if (originList.size() > MAX_LIST_IN_SIZE) {
            List<List<T>> lists = groupList(originList);
            for (List<T> list : lists) {
                consumer.accept(list);
            }
        } else {
            consumer.accept(originList);
        }
    }

    /**
     * list的size超出最大值后，拆分list，分批操作
     * eg：sql语句 in超出最大值后，拆分list，查询
     *
     * @param function
     * @param originList
     * @return void
     * @author daxiong
     * @date 2021/8/4 下午4:31
     */
    public static <T, R> List<R> iterationExecuteFunction(Function<List<T>, List<R>> function, List<T> originList) {
        if (originList.size() > MAX_LIST_IN_SIZE) {
            List<List<T>> lists = groupList(originList);
            List<R> result = new ArrayList<>();
            for (List<T> list : lists) {
                List<R> rList = function.apply(list);
                result.addAll(rList);
            }
            return result;
        } else {
            return function.apply(originList);
        }
    }
}
